<?php

namespace app\devices\command;

use app\devices\service\OrderService;
use think\admin\Command;
use think\admin\Exception;
use think\cache\driver\Redis;
use think\console\Input;
use think\console\Output;

/**
 * 自动清理未付款的箱子订单
 * Class CheckDevice
 * @package app\data\command
 */
class CheckDevice extends Command
{
    protected $redis;
    protected function configure()
    {
        $this->setName('xdevice:ClearNotPayOrder');
        $this->setDescription('清理超时未付款的箱子订单');
        $this->redis = new Redis();
    }

    /**
     * 业务指令执行
     * @param Input $input
     * @param Output $output
     * @return void
     * @throws Exception
     */
    protected function execute(Input $input, Output $output)
    {
        $this->_autoClearDeviceOrder();
        $this->noLockNotice();
    }

    /**
     * 清理超时的箱子订单
     * @throws Exception
     */
    private function _autoClearDeviceOrder()
    {
        try {
            $map =  [
                ['status', '=', 0],
                ['is_check', '=', 0],
                ['create_at', '<', date('Y-m-d H:i:s', strtotime('-2 minute'))]
            ];

            $ids = $this->app->db->name('jcg_devices_order')->where($map)->column('id, box_id, user_id, d_id, is_check', 'id');
            if($ids){
                $arr = array_chunk($ids,1000);
                foreach ($arr as $item){
                    $map = $o_ids = [];
                    foreach ($item as $row){
                        $d_b_ids = $this->redis->handler()->ZRANGE("orderUseBox".$row['d_id'], 0, -1);
                        if(!in_array($row['box_id'], $d_b_ids)){
                            $map[] = ['user_id', '=', $row['user_id']];
                            $map[] = ['id', '=', $row['box_id']];
                        }
                        $o_ids[] = $row['id'];
                    }
                    if($map) $this->app->db->name("jcg_boxs")->whereOr($map)->update(['box_status'=>1, 'user_id'=>0]);
                    if($o_ids) {
                        $this->app->db->name('jcg_devices_order')->where("id", "in", $o_ids)->data(['is_check'=>1])->update();
                    }
                }
                unset($arr, $item, $map, $o_ids, $ids, $d_b_ids);
            }
        } catch (\Exception $exception) {
            $this->queue->error($exception->getMessage().$exception->getTraceAsString());
        }
    }

    /**
     * 箱格忘记关门通知
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     */
    private function noLockNotice(){
        try {
            $list = $this->redis->handler()->ZRANGE("OPENBOX", 0, -1);
            if($list){
                $orderService = new OrderService($this->app);
                foreach ($list as $row){
                    $msg = $this->redis->get($row);
                    if($msg){
                        if(strtotime("+10 minute", $msg[0])<time()){
                            $this->redis->handler()->ZREM($row);
                            $this->redis->delete($row);
                            $orderService->sendTemp($msg[1], $msg[2], $msg[3], '', $msg[4]??'');
                        }
                    }
                }
            }
        }catch (\Exception $e){
            echo $e->getMessage().','.$e->getLine();
        }
    }
}